package com.yuandengta.yomall.order.web;

import com.yuandengta.yomall.order.constant.OrderCheckEnum;
import com.yuandengta.yomall.order.exception.OrderException;
import com.yuandengta.yomall.order.service.AliPayService;
import com.yuandengta.yomall.order.service.OrderService;
import com.yuandengta.yomall.order.vo.OrderConfirmVO;
import com.yuandengta.yomall.order.vo.OrderSubmitResponseVO;
import com.yuandengta.yomall.order.vo.OrderSubmitVO;
import com.yuandengta.yomall.order.vo.PayVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 订单中心 {@link OrderWebController}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AliPayService aliPayService;

    /**
     * 订单确认页
     * @param model
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model, HttpServletRequest request){
        try {
            OrderConfirmVO orderConfirmVO = orderService.confirmOrder();
            model.addAttribute("orderConfirmData", orderConfirmVO);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "confirm";
    }

    /**
     * 下单功能
     *  - 创建订单，验证令牌，锁库存...
     *  - 下单成功跳转到支付页
     *  - 下单失败回到订单确认页，重新确认订单信息
     * @param vo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVO vo, Model model, RedirectAttributes redirectAttributes){
        try {
            OrderSubmitResponseVO responseVO = orderService.submitOrder(vo);
            if (responseVO.getCode() != 0){
                String msg = "下单失败：";
                switch (responseVO.getCode()){
                    case 1: msg += OrderCheckEnum.TOKEN_EXCEPTION.getMsg(); break;
                    case 2: msg += OrderCheckEnum.PRICE_EXCEPTION.getMsg(); break;
                    case 3: msg += OrderCheckEnum.STOCK_EXCEPTION.getMsg(); break;
                    default: msg += "系统未知异常";
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.yomall.com/toTrade";
            }
            model.addAttribute("orderSubmitResponse", responseVO);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "pay";
    }
}
